/// <reference path="../../../../node_modules/@types/clipboard/index.d.ts" />
import {Directive, ElementRef, EventEmitter, Input, OnDestroy, OnInit, Output, Renderer2} from '@angular/core';
import * as ClipboardJS from 'clipboard';
import {timer} from 'rxjs';

@Directive({
  selector: '[ngToolsClipboard]'
})
export class ClipboardDirective implements OnInit, OnDestroy {
  private clipboard;

  @Input('ngToolsClipboard') targetRef: Element;
  @Output() clipboardSuccess: EventEmitter<any> = new EventEmitter();
  @Output() clipboardError: EventEmitter<any> = new EventEmitter();

  constructor(private elemRef: ElementRef, private renderer: Renderer2) {
  }

  ngOnInit(): void {
    this.clipboard = new ClipboardJS(this.elemRef.nativeElement, {
      target: () => this.targetRef
    });
    this.clipboard.on('success', (e) => {
      this.showTip();
      this.clipboardSuccess.emit({target: this.elemRef.nativeElement, event: e});
    });
    this.clipboard.on('error', (e) => {
      this.clipboardError.emit({target: this.elemRef.nativeElement, event: e});
    });
  }

  showTip() {
    const elemTitle = this.elemRef.nativeElement.title; // 保存title
    this.renderer.removeAttribute(this.elemRef.nativeElement, 'title'); // 移除元素的title，避免tooltip插件自动读取title的内容
    const tip = $(this.elemRef.nativeElement).tooltip({
      trigger: 'manual',
      placement: 'right',
      title: () => '已复制'
    });
    tip.tooltip('show');
    this.renderer.setAttribute(this.elemRef.nativeElement, 'title', elemTitle); // 把title加回去
    timer(1000).subscribe(() => {
      tip.tooltip('hide').tooltip('dispose');
    });
  }

  ngOnDestroy(): void {
    if (this.clipboard) {
      this.clipboard.destroy();
    }
  }


}
